package com.neo.controller;

import com.neo.config.DelayedQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @ClassName: SendMsgController
 * @Title: springboot-rabbitmq
 * @Package: com.neo.controller
 * @Description: 发送延时消息
 * @Author: Kisen
 * @Date: 2021/9/25 14:38
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/sendMsg/{message}")
    public void senMsg(@PathVariable String message) {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.info("当前时间：{}，发送一条消息给两个TTL队列：{}", currentTime, message);
        rabbitTemplate.convertAndSend("X", "XA", "消息来自ttl为10s的队列：" + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自ttl为40s的队列：" + message);
    }

    /**
     * 基于死信的消息及过期时间
     *
     * @param message
     * @param ttlTime
     */
    @GetMapping("/sendExpirationMsg/{message}/{ttlTime}")
    public void sendMsg(@PathVariable String message, @PathVariable String ttlTime) {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.info("当前时间：{}，发送一条时长{}毫秒TTL信息给队列QC：{}", currentTime, ttlTime, message);
        rabbitTemplate.convertAndSend("X", "XC", message, messagePostProcessor -> {
            // 发送消息的时候设置过期时长
            messagePostProcessor.getMessageProperties().setExpiration(ttlTime);
            return messagePostProcessor;
        });
    }

    /**
     * 基于插件的消息及延迟的时间
     *
     * @param message
     * @param delayTime
     */
    @GetMapping("/sendDelayMsg/{message}/{delayTime}")
    public void sendMsg(@PathVariable String message, @PathVariable Integer delayTime) {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.info("当前时间：{}，发送一条延迟{}毫秒TTL信息给队列delayed.queue：{}", currentTime, delayTime, message);
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME, DelayedQueueConfig.DELAYED_ROUTING_KEY, message, messagePostProcessor -> {
            // 发送消息的时候设置延迟时长
            messagePostProcessor.getMessageProperties().setDelay(delayTime);
            return messagePostProcessor;
        });

    }
}
